package cn.xfdzx.android.apps.shop.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.adapter.SearchItemAdapter;
import cn.xfdzx.android.apps.shop.adapter.SearchShopsAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.ConfirmGoodBeen;
import cn.xfdzx.android.apps.shop.bean.HomeSearchRetailGoodsBean;
import cn.xfdzx.android.apps.shop.bean.HomeSearchXFDGoodBeen;
import cn.xfdzx.android.apps.shop.bean.HotSearchBeen;
import cn.xfdzx.android.apps.shop.bean.HotSearchRetailBean;
import cn.xfdzx.android.apps.shop.bean.SearchBeen;
import cn.xfdzx.android.apps.shop.bean.SearchShopBean;
import cn.xfdzx.android.apps.shop.contract.HomeSearchContract;
import cn.xfdzx.android.apps.shop.contract.ItemClickListener;
import cn.xfdzx.android.apps.shop.presenter.HomeSearchPresenter;
import cn.xfdzx.android.apps.shop.sql.DatabaseAdaper;
import cn.xfdzx.android.apps.shop.util.KeybordUtil;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.Utils;
import cn.xfdzx.android.apps.shop.util.UtilsData;
import cn.xfdzx.android.apps.shop.view.CheckableTextView;
import cn.xfdzx.android.apps.shop.view.WordWrapView;

import static cn.xfdzx.android.apps.shop.activity.MainActivity.TYPE_IS_RETAIL;


public class HomeSearchActivity extends BaseMvpActivity<HomeSearchPresenter> implements HomeSearchContract.View {

    @BindView(R.id.iv_home_back)
    ImageView ivHomeBack;//返回键
    @BindView(R.id.et_home_search)
    EditText etHomeSearch;//搜索内容框
    @BindView(R.id.iv_home_search_et_delete)
    ImageView ivHomeSearchEtDelete;//清除搜索内容
    @BindView(R.id.tv_home_search)
    TextView tvHomeSearchCancel;//搜索键
    @BindView(R.id.wwv_view)
    WordWrapView wordWrapView;//自动换行历史记录
    @BindView(R.id.wwv_view_resou)
    WordWrapView wwViewResou;//热搜历史记录
    @BindView(R.id.rl_search_history)
    RelativeLayout rlSearchHistory;//历史记录整体
    @BindView(R.id.rl_hot_search_goods)
    RelativeLayout rlHotSearchGoods;//热搜商品
    @BindView(R.id.tv_search_result_comprehensive_sequencing)
    CheckableTextView tvSearchResultComprehensiveSequencing;//综合排序
    @BindView(R.id.tv_search_result_sales)
    CheckableTextView tvSearchResultSales;//销量
    @BindView(R.id.tv_search_result_distance)
    CheckableTextView tvSearchResultDistance;//距离
    @BindView(R.id.tv_search_result_breaks_the_freight)
    CheckableTextView tvSearchResultBreaksTheFreight;//减免运费
    @BindView(R.id.tv_search_result_high_quality_stores)
    CheckableTextView tvSearchResultHighQualityStores;//优质门店
    @BindView(R.id.tv_search_result_members_red_envelope)
    CheckableTextView tvSearchResultMembersRedEnvelope;//会员红包
    @BindView(R.id.tv_search_result_comments_high_marks)
    CheckableTextView tvSearchResultCommentsHighMarks;//点评高分
    @BindView(R.id.ll_state)
    LinearLayout llState;

    @BindView(R.id.rl_search_type)
    RelativeLayout rlSearchType;//商品分类排序
    @BindView(R.id.rv_search_item_type)
    RecyclerView rvSearchItemType;//类别与商铺列表
    @BindView(R.id.rv_search_shops)
    RecyclerView rvSearchShops;//商铺列表
    @BindView(R.id.ll_hint)
    LinearLayout llHint;
    @BindView(R.id.tv_hint)
    TextView tvHint;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    private boolean isComprehensiveSequencing = true;
    private boolean isSales = false;
    private boolean isDistance = false;

    private boolean isBreaksTheFreight = false;
    private boolean isHighQualityStores = false;
    private boolean isMembersRedEnvelope = false;
    private boolean isCommentsHighMarks = false;
    private DatabaseAdaper databaseAdaper;
    private ArrayList<String> searchList;

    private SearchItemAdapter searchItemAdapter;//分类与商店显示
    private SearchShopsAdapter searchShopsAdapter;//商铺列表

    private boolean is_history = false;
    private Dialog dialog;
    private int type = 0;//类别 0-零售 1-批发
    private int page;
    private int limit = Constants.LIMIT;//每页多少条
    private String sid = "";
    private String keyWrod = "";
    private String is_store = "0";//是否查询店铺，1查询
    private String priceOrder = "";
    private String salesOrder = "";
    private RelativeLayout.LayoutParams item_bar;
    private List<HomeSearchXFDGoodBeen.DataBean> mList = new ArrayList<>();
    private String user_curent_lng,user_curent_lat;
    @Override
    public int getLayoutId() {
        return R.layout.activity_home_search;
    }

    @Override
    public void initView() {
        type = TYPE_IS_RETAIL;
        if (type == 0) {
            is_store = "1";
        }
        initHigh();
        user_curent_lng = UtilsData.getPreference(this, "coordinates").getString("coordinates_lng");
        user_curent_lat = UtilsData.getPreference(this, "coordinates").getString("coordinates_lat");

        mPresenter = new HomeSearchPresenter();
        mPresenter.attachView(this);

        databaseAdaper = new DatabaseAdaper(this);
        searchList = databaseAdaper.findAll();

        //类别与商铺的adpter
        rvSearchItemType.setLayoutManager(new LinearLayoutManager(this));
        rvSearchItemType.setItemAnimator(new DefaultItemAnimator());
        searchItemAdapter = new SearchItemAdapter(this, rvSearchItemType, rlSearchType, type);

        rvSearchItemType.setAdapter(searchItemAdapter);
        // 商铺列表
        rvSearchShops.setLayoutManager(new LinearLayoutManager(this));
        rvSearchShops.setItemAnimator(new DefaultItemAnimator());
        searchShopsAdapter = new SearchShopsAdapter(this, mList, type);
        searchShopsAdapter.setOnItemClick(new SearchShopsAdapter.OnItemClick() {
            @Override
            public void setOnItemClick(View view, int position) {
                Intent intent;
                if (type == 0) {
                    intent = new Intent(HomeSearchActivity.this, ShopActivity.class);
                    intent.putExtra("shop_id", mList.get(position).getId() + "");
                } else {
                    intent = new Intent(HomeSearchActivity.this, XFDGoodsDeatailsActivity.class);
                    intent.putExtra("good_id", mList.get(position).getId() + "");
                }
                startActivity(intent);
            }
        });
        rvSearchShops.setAdapter(searchShopsAdapter);

        defultHistroyView();
        public_set();//默认选中
        dialog = Utils.addDialog(this, R.layout.dialog, R.string.are_you_sure_to_delete_all_history, R.string.confirm, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchList.clear();
                databaseAdaper.add(searchList);
                wordWrapView.removeAllViews();
                rlSearchHistory.setVisibility(View.GONE);
                dialog.dismiss();
            }
        });
        etHomeSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (llHint.getVisibility() == View.VISIBLE) {
                    llHint.setVisibility(View.GONE);
                }
                if (editable.toString().trim().length() == 0) {
                    ivHomeSearchEtDelete.setVisibility(View.GONE);
                    if (searchList.size() != 0) {
                        rlSearchHistory.setVisibility(View.VISIBLE);
                    } else {
                        rlSearchHistory.setVisibility(View.GONE);
                    }
                    rlHotSearchGoods.setVisibility(View.VISIBLE);
                    rlSearchType.setVisibility(View.GONE);//商品分类排序
                    rvSearchItemType.setVisibility(View.GONE);
                } else {
                    ivHomeSearchEtDelete.setVisibility(View.VISIBLE);
                    mPresenter.initData(editable.toString().trim(), type + "",user_curent_lng,user_curent_lat);
                    if (is_history) {
                        is_history = false;
                    } else {
                        rlSearchHistory.setVisibility(View.INVISIBLE);
                        rlHotSearchGoods.setVisibility(View.INVISIBLE);
                        rlSearchType.setVisibility(View.GONE);
                        rvSearchItemType.setVisibility(View.VISIBLE);
                    }
                }
            }
        });

        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                page = 1;
                mPresenter.initSearchData(true, true,user_curent_lng,user_curent_lat, sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");

            }
        });
        mPresenter.initHotSearch();


        etHomeSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    ((InputMethodManager) etHomeSearch.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(HomeSearchActivity.this
                                            .getCurrentFocus().getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    // 搜索，进行自己要的操作...
//                    seachList(viewIndex);//这里是我要做的操作！
                    String search_text = etHomeSearch.getText().toString().trim();
                    if (search_text.isEmpty()){
                        Utils.toastMessage(HomeSearchActivity.this,"请输入关键字");
                    }else {
                        if (search_text.length() != 0) {
                            if (searchList.contains(search_text)) {
                                searchList.remove(searchList.indexOf(search_text));
                                searchList.add(0, search_text);
                            } else {
                                searchList.add(0, search_text);
                            }
                            databaseAdaper.add(searchList);
                            wordWrapView.removeAllViews();
                            defultHistroyView();
                            setData();
                        }
                        page = 1;

                        keyWrod = search_text;
                        priceOrder = "";
                        salesOrder = "";
                        mPresenter.initSearchData(true, true, user_curent_lng, user_curent_lat, sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");
                    }
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    private void initHigh() {
        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(this);
        llState.setLayoutParams(item_bar);
    }

    @Override
    protected void onDestroy() {
        if (searchList != null) {
            searchList.clear();
            searchList = null;
        }
        mList.clear();
        mList = null;
        super.onDestroy();
    }

    private void defultHistroyView() {
        for (final String search_text : searchList) {
            final TextView textview = (TextView) View.inflate(this, R.layout.item_search_history, null);
            textview.setText(search_text);
            textview.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    is_history = true;
                    etHomeSearch.setText(search_text);
                    etHomeSearch.setSelection(etHomeSearch.getText().length());
                    KeybordUtil.closeKeybord(HomeSearchActivity.this);

                    searchList.remove(searchList.indexOf(search_text));
                    searchList.add(0, search_text);
                    databaseAdaper.add(searchList);
                    wordWrapView.removeAllViews();
                    defultHistroyView();
                    setData();
                    page = 1;

                    keyWrod = search_text;
                    priceOrder = "";
                    salesOrder = "";
                    mPresenter.initSearchData(true, true,user_curent_lng,user_curent_lat, sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");
                }
            });
            wordWrapView.addView(textview);
        }
        if (searchList.size() == 0) {
            rlSearchHistory.setVisibility(View.GONE);
        } else {
            rlSearchHistory.setVisibility(View.VISIBLE);
        }

    }


    @OnClick({R.id.iv_home_back, R.id.iv_home_search_et_delete, R.id.tv_home_search, R.id.iv_home_search_delete, R.id.tv_search_result_comprehensive_sequencing, R.id.tv_search_result_sales, R.id.tv_search_result_distance, R.id.tv_search_result_breaks_the_freight, R.id.tv_search_result_high_quality_stores, R.id.tv_search_result_members_red_envelope, R.id.tv_search_result_comments_high_marks})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_home_back:
                finish();
                break;
            case R.id.iv_home_search_et_delete:
                etHomeSearch.getText().clear();
                break;
            case R.id.tv_home_search:
                String search_text = etHomeSearch.getText().toString().trim();
                if (search_text.isEmpty()){
                    Utils.toastMessage(this,"请输入关键字");
                }else {
                    if (search_text.length() != 0) {
                        if (searchList.contains(search_text)) {
                            searchList.remove(searchList.indexOf(search_text));
                            searchList.add(0, search_text);
                        } else {
                            searchList.add(0, search_text);
                        }
                        databaseAdaper.add(searchList);
                        wordWrapView.removeAllViews();
                        defultHistroyView();
                        setData();
                    }
                    page = 1;

                    keyWrod = search_text;
                    priceOrder = "";
                    salesOrder = "";
                    mPresenter.initSearchData(true, true, user_curent_lng, user_curent_lat, sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");
                }
                break;
            case R.id.iv_home_search_delete:

                dialog.show();
                break;

            case R.id.tv_search_result_comprehensive_sequencing://综合排序
                if (!isComprehensiveSequencing) {
                    isComprehensiveSequencing = true;
                    isSales = false;
                    isDistance = false;
                    public_set();
                    page = 1;
                    priceOrder = "";
                    salesOrder = "";
                    mPresenter.initSearchData(true, true, user_curent_lng,user_curent_lat,sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");
                }
                break;
            case R.id.tv_search_result_sales://销量
                if (!isSales) {
                    isComprehensiveSequencing = false;
                    isSales = true;
                    isDistance = false;
                    public_set();
                    page = 1;
                    priceOrder = "";
                    salesOrder = "desc";
                    mPresenter.initSearchData(true, true,user_curent_lng,user_curent_lat, sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");
                }
                break;
            case R.id.tv_search_result_distance://距离
                Toast.makeText(this, "距离功能暂未开放", Toast.LENGTH_SHORT).show();
//                if (!isDistance) {
//                    isComprehensiveSequencing = false;
//                    isSales = false;
//                    isDistance = true;
//                    public_set();
//                    page=1;
//                priceOrder="";
//                salesOrder="";
//                    mPresenter.initSearchData(true,true,sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");
//                }
                break;

            case R.id.tv_search_result_breaks_the_freight://减免运费
                isBreaksTheFreight = !isBreaksTheFreight;
                tvSearchResultBreaksTheFreight.setChecked(isBreaksTheFreight);

                break;
            case R.id.tv_search_result_high_quality_stores://优质门店
                isHighQualityStores = !isHighQualityStores;
                tvSearchResultHighQualityStores.setChecked(isHighQualityStores);

                break;
            case R.id.tv_search_result_members_red_envelope://会员红包
                isMembersRedEnvelope = !isMembersRedEnvelope;
                tvSearchResultMembersRedEnvelope.setChecked(isMembersRedEnvelope);

                break;
            case R.id.tv_search_result_comments_high_marks://点评高分
                isCommentsHighMarks = !isCommentsHighMarks;
                tvSearchResultCommentsHighMarks.setChecked(isCommentsHighMarks);

                break;
        }
    }

    /**
     * 点击历史，搜索
     */
    public void setData() {
        rlSearchHistory.setVisibility(View.INVISIBLE);
        rlHotSearchGoods.setVisibility(View.INVISIBLE);
        rlSearchType.setVisibility(View.VISIBLE);
        rvSearchItemType.setVisibility(View.GONE);

        isComprehensiveSequencing = true;
        isSales = false;
        isDistance = false;

        isBreaksTheFreight = false;
        isHighQualityStores = false;
        isMembersRedEnvelope = false;
        isCommentsHighMarks = false;
        public_set();

        tvSearchResultBreaksTheFreight.setChecked(isBreaksTheFreight);
        tvSearchResultHighQualityStores.setChecked(isHighQualityStores);
        tvSearchResultMembersRedEnvelope.setChecked(isMembersRedEnvelope);
        tvSearchResultCommentsHighMarks.setChecked(isCommentsHighMarks);

        if (type == 0) {
            tvSearchResultBreaksTheFreight.setVisibility(View.VISIBLE);
            tvSearchResultHighQualityStores.setVisibility(View.VISIBLE);
            tvSearchResultMembersRedEnvelope.setVisibility(View.VISIBLE);
            tvSearchResultCommentsHighMarks.setVisibility(View.VISIBLE);
        } else {
            tvSearchResultBreaksTheFreight.setVisibility(View.GONE);
            tvSearchResultHighQualityStores.setVisibility(View.GONE);
            tvSearchResultMembersRedEnvelope.setVisibility(View.GONE);
            tvSearchResultCommentsHighMarks.setVisibility(View.GONE);
        }
    }

    @Override
    public void showLoading() {
        if (!ProgressDialog.getInstance().materialDialog.isShowing()) {
            ProgressDialog.getInstance().show(this);
        }
    }

    @Override
    public void hideLoading() {

            ProgressDialog.getInstance().dismiss();

    }

    @Override
    public void finishRefresh() {
        mRefreshLayout.finishRefresh(true);//刷新完成
    }

    @Override
    public void finishLoadMore() {
        mRefreshLayout.finishLoadMore(true);//加载完成
    }

    @Override
    public void onError(Throwable throwable) {
        Toast.makeText(this, "网络请求出错", Toast.LENGTH_SHORT).show();
    }


    /**
     * 搜索出的类别与店铺列表
     *
     * @param bean
     */
    @Override
    public void onInitDataSuccess(SearchBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            searchItemAdapter.setData(bean,keyWrod);
            searchItemAdapter.setOnItemClickListener(new ItemClickListener() {
                @Override
                public void onItemClick(int position) {

                    page = 1;
                    keyWrod = bean.getData().getGoods().get(position).getTitle();
                    etHomeSearch.setText(keyWrod);
                    etHomeSearch.setSelection(keyWrod.length());
                    if (keyWrod.length() != 0) {
                        if (searchList.contains(keyWrod)) {
                            searchList.remove(searchList.indexOf(keyWrod));
                            searchList.add(0, keyWrod);
                        } else {
                            searchList.add(0, keyWrod);
                        }
                        databaseAdaper.add(searchList);
                        wordWrapView.removeAllViews();
                        defultHistroyView();
                        setData();
                    }
                    //priceOrder    按价格排序 desc/asc
                    //salesOrder    按销售量排序 desc/asc
                    //news    是否是新品 1是 0否
                    priceOrder = "";
                    salesOrder = "";
                    mPresenter.initSearchData(true, true,user_curent_lng,user_curent_lat, sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");
                }
            });
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onHotSearchSuccess(HotSearchBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            for (final String search_text : bean.getData()) {
                final TextView textview = (TextView) View.inflate(this, R.layout.item_search_history, null);
                textview.setText(search_text);
                textview.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        is_history = true;
                        etHomeSearch.setText(search_text);
                        etHomeSearch.setSelection(etHomeSearch.getText().length());
                        KeybordUtil.closeKeybord(HomeSearchActivity.this);

                        searchList.add(0, search_text);
                        databaseAdaper.add(searchList);
                        wordWrapView.removeAllViews();
                        defultHistroyView();
                        setData();
                        page = 1;

                        keyWrod = search_text;
                        priceOrder = "";
                        salesOrder = "";
                        mPresenter.initSearchData(true, true, user_curent_lng,user_curent_lat,sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");
                    }
                });
                wwViewResou.addView(textview);
            }
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * @param bean
     */
    @Override
    public void onInitSearchDataSuccess(HomeSearchXFDGoodBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (page == 1) {
                mList.clear();
                mRefreshLayout.setNoMoreData(false);
                mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                    @Override
                    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                        mPresenter.initSearchData(false, false,user_curent_lng,user_curent_lat, sid, page + "", limit + "", type + "", is_store, "", keyWrod, priceOrder, salesOrder, "");

                    }
                });
            }
            if (bean.getData().size() == 0) {
                if (page == 1) {
                    llHint.setVisibility(View.VISIBLE);
                    tvHint.setText("没有找到"+etHomeSearch.getText().toString().trim());
                }
                mRefreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                page++;
                mList.addAll(bean.getData());
                searchShopsAdapter.notifyDataSetChanged();
            }
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onGetSearchShopListSuccess(SearchShopBean bean) {

    }

    @Override
    public void onGetSearchGoodsListSuccess(HomeSearchRetailGoodsBean bean) {

    }

    @Override
    public void onAddCarSuccess(ConfirmGoodBeen bean) {

    }

    @Override
    public void onGetRetailHotSearchSuccess(HotSearchRetailBean bean) {

    }


    private void public_set() {
        tvSearchResultComprehensiveSequencing.setChecked(isComprehensiveSequencing);
        tvSearchResultSales.setChecked(isSales);
        tvSearchResultDistance.setChecked(isDistance);
    }


}
